package concurrencyPractice.chapter06;

import java.util.*;
import java.util.concurrent.*;

/**
 * @author xinya
 * @version 1.0
 * @project javacore
 * @description 6-17 在预定时间内请求旅游报价
 * @date 2024/1/4 09:48:32
 */
public class QuoteTask<TravelQuote, TravelInfo> implements Callable<TravelQuote> {
    private final TravelCompany company;
    private final TravelInfo travelInfo;

    private static final ExecutorService exec = Executors.newFixedThreadPool(10);

    QuoteTask(TravelCompany travelCompany, TravelInfo travelInfo) {
        this.company = travelCompany;
        this.travelInfo = travelInfo;
    }

    public TravelQuote call() throws Exception {
        return company.solicitQuote(travelInfo);
    }

    public List<TravelQuote> getRankedTravelQuotes(TravelInfo travelInfo, Set<TravelCompany> companies, Comparator<TravelQuote> ranking, long time, TimeUnit unit) throws InterruptedException {
        List<QuoteTask> tasks = new ArrayList<>();
        for (TravelCompany company : companies
        ) {
            tasks.add(new QuoteTask(company, travelInfo));
        }
        List<Future<TravelQuote>> futures = exec.invokeAll(tasks, time, unit);

        List<TravelQuote> quotes = new ArrayList<>(tasks.size());

        Iterator<QuoteTask> taskIter = tasks.iterator();
        for (Future<TravelQuote> f : futures
        ) {
            QuoteTask task = taskIter.next();

            try {
                quotes.add(f.get());
            } catch (ExecutionException e) {
                quotes.add(task.getFailureQuote(e.getCause()));
            } catch (CancellationException e) {
                quotes.add(task.getTimeoutQuote(e));
            }
        }

        Collections.sort(quotes, ranking);
        return quotes;
    }


    final class TravelCompany {
        TravelQuote solicitQuote(TravelInfo travelInfo) {
            return null;
        }
    }
}
